package codename.carrot.bomberman.activity;

import java.util.HashMap;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import codename.carrot.bomberman.LevelDefinition;
import codename.carrot.bomberman.LevelReader;
import codename.carrot.bomberman.R;
import codename.carrot.bomberman.game.gamemessages.GameInitMessage;
import codename.carrot.bomberman.game.gamemessages.PlayerJoinMessage;
import codename.carrot.bomberman.game.gamemessages.PlayerQuitMessage;
import codename.carrot.bomberman.game.networkobjects.DroidPoint;
import codename.carrot.bomberman.models.Player;
import codename.carrot.bomberman.network.NetworkConnection;
import codename.carrot.bomberman.network.client.ClientPostOffice;
import codename.carrot.bomberman.network.server.ServerPostOffice;

/**
 * Activity that represents the gamelobby as used by the game's host
 * 
 * @author Group A4
 */

public class ServerGameLobbyActivity extends GameLobbyActivity { 
	/**
	 * The textview that displays the selected level.
	 */
     private TextView tvLevelname;
     /**
      * Button for launching the level selector.
      */
     private Button btnSelectLevel;
     /**
      * The level definition for loading levels.
      */
     private LevelDefinition levelDefinition;
     
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//SET UP SERVER
        ServerPostOffice.getInstance(); // Make sure the server post office is ready to handle shit from clients.
		NetworkConnection.getInstance().connectAsServer();
		
		TextView tvLocalIpAdress = (TextView) this.findViewById(R.id.tvLocalIpAddress);
		tvLevelname = (TextView) findViewById(R.id.tvLevelname);
		tvLocalIpAdress.setText("Server IP: " + ipString);
		tvLocalIpAdress.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.VISIBLE);

		RelativeLayout rlFooter = (RelativeLayout) findViewById(R.id.rlGameLobbyFooter);
		RelativeLayout footer = (RelativeLayout) View.inflate(this, R.layout.host_game_footer, rlFooter);
		btnStartGame = (Button) footer.findViewById(R.id.btnStartGame);
		btnSelectLevel = (Button) footer.findViewById(R.id.btnSelectLevel);
		btnStartGame.setEnabled(false);
		btnStartGame.setOnClickListener(this);	    
		btnSelectLevel.setOnClickListener(this);
		 
		// Create the player used by the host
        myPlayer = new Player(0, 0, 0, nickname);
        
        //SEND A PLAYER JOIN MESSAGE TO THE SERVER.
		PlayerJoinMessage pm = new PlayerJoinMessage(nickname);
		ClientPostOffice.getInstance().sendMessage(pm);
    }   


	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);        
        if(resultCode == RESULT_OK && requestCode == LevelViewerActivity.REQUEST_CODE) {
            String levelName = data.getExtras().getString(LevelViewerActivity.RESULT_LEVEL_NAME);
            // Load the leveldefinition
            LevelReader levelReader = new LevelReader(this);            
            try {
                levelReader.readLevel(levelName);
                levelDefinition = levelReader.getLevelDefinition();
                tvLevelname.setText("Level: " + levelName.substring(0, levelName.length()-4));
                tvLevelname.setVisibility(View.VISIBLE);
            }
            catch(Exception e) {
                Toast.makeText(this, "Could not read selected level. Try again, or change to another level.", Toast.LENGTH_LONG).show();
            }
        }
    }
	
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
	
    @Override
	public void onClick(View v) {
	    if(v == btnSelectLevel) {
	        Intent intent = new Intent(this, LevelViewerActivity.class);
	        this.startActivityForResult(intent, LevelViewerActivity.REQUEST_CODE);
	    }
	    else if(v == btnStartGame) {
	        if(levelDefinition == null) {
	            Toast.makeText(this, "You need to select a level first.", Toast.LENGTH_LONG).show();
	            return;
	        }
	        if(playerArray.getCount() < 2) {
	            Toast.makeText(this, "You need to wait for at least 1 additional player", Toast.LENGTH_LONG).show();
	            return;
	        }
	        // Start game.. need to create an GameInitMessage
	        HashMap<Integer, DroidPoint> initialPositions = new HashMap<Integer, DroidPoint>();
	        DroidPoint[] positions = new DroidPoint[4];
	        positions[0] = levelDefinition.getStartPos(LevelDefinition.COLOR_BLUE);
	        positions[1] = levelDefinition.getStartPos(LevelDefinition.COLOR_ORANGE);
	        positions[2] = levelDefinition.getStartPos(LevelDefinition.COLOR_YELLOW);
	        positions[3] = levelDefinition.getStartPos(LevelDefinition.COLOR_PURPLE);
	        for(int i=0; i < playerArray.getCount(); i++) {
	            if(i < 4) {
	                Player p = playerArray.getItem(i);	           
	                initialPositions.put(p.getPlayerId(), positions[i]);
	            }
	        }	        	        	      
	        GameInitMessage gameInitMessage = new GameInitMessage(levelDefinition, initialPositions);                  
	        
	        // Send the gameInitMessage to all connected clients
	        ClientPostOffice.getInstance().sendMessage(gameInitMessage);	       
	    }	    	    	  
	}
		
	
	@Override
    public void onPlayerJoin(PlayerJoinMessage pm, int playerId) {
        super.onPlayerJoin(pm, playerId);
        // Count number of players. If > 1, startbutton should be enabled
        if(playerArray.getCount() > 1) btnStartGame.setEnabled(true);
    }


    @Override
    public void onPlayerQuit(PlayerQuitMessage pm) {
        super.onPlayerQuit(pm);
        // Count number of players, if < 2, startbutton should be disabled
        if(playerArray.getCount() < 2) btnStartGame.setEnabled(false);
    }

}
